import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_aygsh/util/GridPage.dart';
import '../util/AppSaveInfoUtil.dart';
import '../util/SignUtil.dart';
import '../base/application.dart';
import '../http/HttpUtil.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/util/LoadingUtil.dart';
import './ShopperOrderPay.dart';

class BecomeShopperPage extends StatefulWidget {
  BecomeShopperPage({Key key}) : super(key: key);

  @override
  _BecomeShopperPageState createState() => _BecomeShopperPageState();
}

class _BecomeShopperPageState extends State<BecomeShopperPage> {
  EasyRefreshController _controller = EasyRefreshController();
  //
  //fuwushang_bg
  //icon_shenfen
  String price1 = '0';
  String price2 = '0';
  String token = '';
  String group_id = "1";
  String nickname = "";
  List datas = [
    {"name": "年费制", "icon": "tequan_nianfei"},
    {"name": "折上9.8折", "icon": "tequan_zhekou"},
    {"name": "无限免邮", "icon": "tequan_mianyou"},
    {"name": "生日惊喜", "icon": "tequan_shengri"},
    {"name": "尊享客服", "icon": "tequan_kefu"},
    {"name": "分享赚", "icon": "tequan_fenxiangzhuan"},
    {"name": "税费券", "icon": "tequan_shuifeiquan"},
    {"name": "极速退款", "icon": "tequan_tuikuan"}
  ];
  // List<Widget> list = List();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text('成为店主',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: Container(
          color: black,
          child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              controller: _controller,
              header: MaterialHeader(),
              child: CustomScrollView(shrinkWrap: true, slivers: <Widget>[
                SliverToBoxAdapter(
                    child: group_id == '1'
                        ? Container(
                            child: Column(children: <Widget>[
                            Container(
                                width: ScreenUtil.getInstance().setWidth(750) -
                                    2 * kMargin20,
                                height:
                                    (ScreenUtil.getInstance().setWidth(750) -
                                            2 * kMargin20) *
                                        0.6,
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image:
                                            AssetImage('images/dianzhu_bg.png'),
                                        fit: BoxFit.fill)),
                                margin: EdgeInsets.all(kMargin10),
                                child: Container(
                                  padding: EdgeInsets.all(kMargin30),
                                  child: Column(
                                    children: <Widget>[
                                      Row(
                                        children: <Widget>[
                                          Image.asset(
                                              'images/icon_shenfen.png'),
                                          Text(
                                            '日尚臻选店主',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(BIG_FONT_SIZE),
                                                color: hexToColor('#f3cead')),
                                          )
                                        ],
                                      ),
                                      Container(
                                        height: kMargin10,
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Expanded(
                                              child: Container(
                                                  alignment: Alignment.center,
                                                  child: Text(
                                                    '"我要享受店主的折扣，我想要实时分享的收益"',
                                                    style: TextStyle(
                                                      fontSize: ScreenUtil
                                                              .getInstance()
                                                          .setSp(
                                                              MINI_FONT_SIZE),
                                                      color:
                                                          hexToColor('#f3cead'),
                                                    ),
                                                  )))
                                        ],
                                      ),
                                      Container(
                                        height: kMargin60,
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Text(
                                            '按去年用户消费',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(MINI_FONT_SIZE),
                                                color: hexToColor('#f3cead')),
                                          )
                                        ],
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Text(
                                            '计算一年可省+赚',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(MINI_FONT_SIZE),
                                                color: hexToColor('#f3cead')),
                                          )
                                        ],
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Expanded(
                                            child: Text(
                                              '¥' + price1,
                                              style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(BIG_FONT_SIZE),
                                                  color: hexToColor('#f3cead')),
                                            ),
                                          ),
                                          RaisedButton(
                                            child: Text('立即开通',
                                                style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(
                                                              SMALL_FONT_SIZE),
                                                )),
                                            textColor: Colors.red,
                                            // elevation: 20,
                                            shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(20)),
                                            color: Color.fromRGBO(
                                                255, 255, 255, 1),
                                            onPressed: () {
                                              showCupertinoDialog(
                                                  context: context,
                                                  builder: (context) {
                                                    return CupertinoAlertDialog(
                                                      title: Text('请输入邀请人'),
                                                      content: Card(
                                                        elevation: 0.0,
                                                        child: Column(
                                                          children: <Widget>[
                                                            TextField(
                                                              onChanged:
                                                                  (value) {
                                                                nickname =
                                                                    value;
                                                              },
                                                              cursorColor:
                                                                  mainColor,
                                                              decoration: InputDecoration(
                                                                  hintText:
                                                                      '手机号或邀请码',
                                                                  border:
                                                                      InputBorder
                                                                          .none,
                                                                  filled: true,
                                                                  fillColor: Colors
                                                                      .grey
                                                                      .shade50),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                      actions: <Widget>[
                                                        CupertinoDialogAction(
                                                          onPressed: () {
                                                            Navigator.pop(
                                                                context);
                                                          },
                                                          child: Text('取消',
                                                              style: TextStyle(
                                                                  color:
                                                                      black_99)),
                                                        ),
                                                        CupertinoDialogAction(
                                                          onPressed: () {
                                                            Navigator.pop(
                                                                context);
                                                            showDialog(
                                                                context:
                                                                    context,
                                                                barrierDismissible:
                                                                    false,
                                                                builder: (_) {
                                                                  return new NetLoadingDialog(
                                                                    loadingText:
                                                                        "下单中...",
                                                                    bgColor: Color
                                                                        .fromARGB(
                                                                            255,
                                                                            0,
                                                                            0,
                                                                            0),
                                                                    requestCallBack:
                                                                        null,
                                                                    outsideDismiss:
                                                                        false,
                                                                  );
                                                                });
                                                            buy('1');
                                                          },
                                                          child: Text('确定',
                                                              style: TextStyle(
                                                                  color:
                                                                      mainColor)),
                                                        ),
                                                      ],
                                                    );
                                                  });
                                            },
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                )),
                            Container(
                              alignment: Alignment.centerLeft,
                              margin: EdgeInsets.all(kMargin20),
                              child: Text(
                                '特权介绍',
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(BIG_FONT_SIZE),
                                    color: hexToColor('#d0ab70')),
                              ),
                            )
                          ]))
                        : Center()),
                SliverGrid(
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent:
                        ScreenUtil.getInstance().setWidth(750) / 4,
                    mainAxisSpacing: 0,
                    crossAxisSpacing: 0,
                    childAspectRatio: 1, //子控件宽高比
                  ),
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      return getItemContainer(context, index);
                    },
                    childCount: datas.length,
                  ),
                ),
                SliverToBoxAdapter(
                    child: group_id == '2'
                        ? Container(
                            child: Column(children: <Widget>[
                            Container(
                                padding: EdgeInsets.all(kMargin30),
                                width: ScreenUtil.getInstance().setWidth(750) -
                                    2 * kMargin20,
                                height:
                                    (ScreenUtil.getInstance().setWidth(750) -
                                            2 * kMargin20) *
                                        0.6,
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: AssetImage(
                                            'images/fuwushang_bg.png'),
                                        fit: BoxFit.fill)),
                                margin: EdgeInsets.all(kMargin10),
                                child: Container(
                                  child: Column(
                                    children: <Widget>[
                                      Row(
                                        children: <Widget>[
                                          Image.asset(
                                              'images/icon_shenfen.png'),
                                          Text(
                                            '日尚臻选服务商',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(BIG_FONT_SIZE),
                                                color: hexToColor('#f3cead')),
                                          )
                                        ],
                                      ),
                                      Container(
                                        height: kMargin10,
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Expanded(
                                              child: Container(
                                                  alignment: Alignment.center,
                                                  child: Text(
                                                    '"除了更好的店主折扣，我要多一份收入，尝试轻松创业"',
                                                    style: TextStyle(
                                                      fontSize: ScreenUtil
                                                              .getInstance()
                                                          .setSp(
                                                              MINI_FONT_SIZE),
                                                      color:
                                                          hexToColor('#f3cead'),
                                                    ),
                                                  )))
                                        ],
                                      ),
                                      Container(
                                        height: kMargin60,
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Text(
                                            '按去年用户消费',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(MINI_FONT_SIZE),
                                                color: hexToColor('#f3cead')),
                                          )
                                        ],
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Text(
                                            '计算一年可省+赚',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(MINI_FONT_SIZE),
                                                color: hexToColor('#f3cead')),
                                          )
                                        ],
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Expanded(
                                            child: Text(
                                              '¥' + price2,
                                              style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(BIG_FONT_SIZE),
                                                  color: hexToColor('#f3cead')),
                                            ),
                                          ),
                                          RaisedButton(
                                            child: Text('立即开通',
                                                style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(
                                                              SMALL_FONT_SIZE),
                                                )),
                                            textColor: Colors.red,
                                            // elevation: 20,
                                            shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(20)),
                                            color: Color.fromRGBO(
                                                255, 255, 255, 1),
                                            onPressed: () {
                                              showCupertinoDialog(
                                                  context: context,
                                                  builder: (context) {
                                                    return CupertinoAlertDialog(
                                                      title: Text('请输入邀请人'),
                                                      content: Card(
                                                        elevation: 0.0,
                                                        child: Column(
                                                          children: <Widget>[
                                                            TextField(
                                                              onChanged:
                                                                  (value) {
                                                                nickname =
                                                                    value;
                                                              },
                                                              cursorColor:
                                                                  mainColor,
                                                              decoration: InputDecoration(
                                                                  hintText:
                                                                      '手机号或邀请码',
                                                                  border:
                                                                      InputBorder
                                                                          .none,
                                                                  filled: true,
                                                                  fillColor: Colors
                                                                      .grey
                                                                      .shade50),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                      actions: <Widget>[
                                                        CupertinoDialogAction(
                                                          onPressed: () {
                                                            Navigator.pop(
                                                                context);
                                                          },
                                                          child: Text('取消',
                                                              style: TextStyle(
                                                                  color:
                                                                      black_99)),
                                                        ),
                                                        CupertinoDialogAction(
                                                          onPressed: () {
                                                            Navigator.pop(
                                                                context);
                                                            showDialog(
                                                                context:
                                                                    context,
                                                                barrierDismissible:
                                                                    false,
                                                                builder: (_) {
                                                                  return new NetLoadingDialog(
                                                                    loadingText:
                                                                        "下单中...",
                                                                    bgColor: Color
                                                                        .fromARGB(
                                                                            255,
                                                                            0,
                                                                            0,
                                                                            0),
                                                                    requestCallBack:
                                                                        null,
                                                                    outsideDismiss:
                                                                        false,
                                                                  );
                                                                });
                                                            buy('2');
                                                          },
                                                          child: Text('确定',
                                                              style: TextStyle(
                                                                  color:
                                                                      mainColor)),
                                                        ),
                                                      ],
                                                    );
                                                  });
                                            },
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                )),
                            Container(
                              alignment: Alignment.centerLeft,
                              margin: EdgeInsets.all(kMargin20),
                              child: Text(
                                '特权介绍',
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(BIG_FONT_SIZE),
                                    color: hexToColor('#d0ab70')),
                              ),
                            )
                          ]))
                        : Center()),
                SliverGrid(
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent:
                        ScreenUtil.getInstance().setWidth(750) / 4,
                    mainAxisSpacing: 0,
                    crossAxisSpacing: 0,
                    childAspectRatio: 1, //子控件宽高比
                  ),
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      return getItemContainer(context, index);
                    },
                    childCount: datas.length,
                  ),
                ),
              ]))),
    );
  }

  getItemContainer(BuildContext context, int index) {
    return GestureDetector(
      child: new Column(
        children: <Widget>[
          Image.asset('images/' + datas[index]['icon'] + '.png',
              width: ScreenUtil.getInstance().setWidth(DP_90),
              height: ScreenUtil.getInstance().setWidth(DP_90)),
          Padding(
            padding: EdgeInsets.all(5),
            child: Text(
              datas[index]['name'],
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
                  color: hexToColor('#d0ab70')),
            ),
          )
        ],
      ),
      onTap: () {},
    );
  }

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      if (value == null) {
        // Navigator.of(context).pushNamed('login');
      } else {
        token = value;
        group_id = APPLIC.userInfoMap['user_msg']['group_id'].toString();
        getGoodMsg('1');
        getGoodMsg('2');
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    // WidgetsBinding.instance.removeObserver(this);
  }

  buy(String goods_id) async {
    Map map = new Map();
    map['goods_id'] = goods_id;
    map['token'] = token;
    map['referrer'] = nickname;
    map['sign_type'] = createSignType(Api.URL_VIPGoodsOrder);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_VIPGoodsOrder, data: getSign(map));
    Navigator.of(context).pop(1);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      // {code: 1, msg: 成功, data: {order_id: 2, order_num: 5eb2617677221839, title: 升级店主, pay_price: 1000}}
      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        return new ShopperOrderPay(
            orderId: userMap['data']['order_id'],
            title: userMap['data']['title'],
            orderNum: userMap['data']['order_num'],
            totalMoney: userMap['data']['pay_price'].toString());
      }));
    }else{
      Fluttertoast.showToast(msg: userMap['msg']);
    }
  }

  getGoodMsg(String goods_id) async {
    Map map = new Map();
    map['goods_id'] = goods_id;
    map['sign_type'] = createSignType(Api.URL_VIPGoods);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_VIPGoods, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        if (goods_id == '1') {
          //升级店主
          price1 = userMap['data']['goodsMsg']['price'].toString();
        }
        if (goods_id == '2') {
          //升级服务商
          price2 = userMap['data']['goodsMsg']['price'].toString();
        }
      });
    }
  }
}
